package com.letoy.study.service.Impl;


import com.letoy.study.entity.AuthUser;
import com.letoy.study.entity.User;
import com.letoy.study.service.MyAuthUserService;
import com.letoy.study.service.UserService;
import com.letoy.study.utils.BCryptPasswordEncoderUtil;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 要实现UserDetailsService接口，这个接口是security提供的
 */
@Service
public class MyAuthUserDetailsServiceImpl implements MyAuthUserService {

    @Resource
    UserService userService;

    @Override
    public AuthUser getUserByEmailPassword(String email, String password) throws UsernameNotFoundException {
        BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil = new BCryptPasswordEncoderUtil();
        User user = userService.getUserByEmail(email);
        if (!bCryptPasswordEncoderUtil.matches(password,user.getPassword())) {
            throw new UsernameNotFoundException(String.format("用户%s. 密码错误", email));
        } else {
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(user.getRole()));
            return new AuthUser(email , user.getName(), "", user.getUserId(), user.getPassword(), 0, authorities);
        }
    }

    @Override
    public AuthUser getUserByUserId(String userId) {
        AuthUser authUser = new AuthUser();
        User user = userService.getUserByUserId(userId);
        authUser.setEmail(user.getEmail());
        authUser.setId(user.getUserId());
        return authUser;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;
    }
}
